﻿using System.IO;
using System.Linq;
using System.Resources;

namespace System.Reflection
{
    public static class AssemblyExtension
    {
        public static Stream GetEmbeddedResource(this Assembly assembly, string resourceName)
        {
            byte[] res;
            if (!assembly.GetEmbeddedResource(resourceName, out res))
                return null;
            return new MemoryStream(res);
        }

        public static bool GetEmbeddedResource(this Assembly assembly, string resourceName, out byte[] resource)
        {
            resource = null;
            string[] manifestResourceNames = assembly.GetManifestResourceNames();
            string baseName = assembly.FullName;
            baseName = baseName.Substring(0, baseName.IndexOf(",")) + ".g";
            if (!manifestResourceNames.Contains(baseName + ".resources"))
                return false;
            ResourceManager manager = new ResourceManager(baseName, assembly);
            UnmanagedMemoryStream stream = manager.GetStream(resourceName);
            if (stream == null)
                return false;
            try
            {
                resource = new byte[stream.Length];
                stream.Read(resource, 0, (int)stream.Length);
            }
            finally
            {
                stream.Dispose();
            }
            return true;
        }
    }
}